//
//  FDHttpTool.m
//  FD
//
//  Created by Yasin on 2018/10/11.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  网络请求


#import "FDHttpTool.h"
#import <AFNetworking.h>
@implementation FDHttpTool
+ (void)requestWithPara:(NSDictionary *)para successBlock:(FDHttpSuccessBlock)succe failureBlock:(FDHttpFailureBlock)failure {
    

    AFHTTPSessionManager *sessonManager = [self configureAFSessionManager];
}
// 配置AFHTTPSessionManager
+ (AFHTTPSessionManager *)configureAFSessionManager {
    
    AFSecurityPolicy *securityPolicy=[[AFSecurityPolicy alloc]init];
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPSessionManager *sessionManager=[AFHTTPSessionManager  manager];
    [sessionManager setSecurityPolicy:securityPolicy];
    sessionManager.responseSerializer=[AFHTTPResponseSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    
    //设置超时时间
    [sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionManager.requestSerializer.timeoutInterval = 5.0f;
    [sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    return sessionManager;
}


//+ (void)rb_POSTWithURL:(NSString *)urlStr authr:(NSString *)authr params:(NSDictionary *)parDic successHandler:(FDHttpSuccessBlock)success failureHandler:(FDHttpFailureBlock)failure
+ (void)rb_POSTWithURL:(NSString *)urlStr authr:(NSString *)authr timeStampStr:(NSString *)stampStr params:(NSDictionary *)parDic successHandler:(FDHttpSuccessBlock)success failureHandler:(FDHttpFailureBlock)failure
{
    // 先将dic转JSON
    NSString *jsonStr = [self rb_jsonStrFromDic:parDic];
    
    //一 创建请求类,并设置请求头、请求体 就这样写 可用
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
    req.timeoutInterval = 5;
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 
    [req setValue:authr forHTTPHeaderField:@"Authorization"];
    [req setValue:@"1.0.0" forHTTPHeaderField:@"Authorization-Version"]; //版本
    [req setValue:stampStr forHTTPHeaderField:@"Authorization-Timestamp"]; //时间戳
    [req setValue:@"ios" forHTTPHeaderField:@"authorization-device"]; //设备
    [req setValue:@"zh-CN" forHTTPHeaderField:@"Accept-Language"]; //语言
    
    // 设置请求体: ⚠️❗️
    [req setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    NSLog(@"1111111:%@",[req allHTTPHeaderFields]);
    NSLog(@"2222222:%@",urlStr);
    
    // 二 AFURLSessionManager
    AFURLSessionManager *manger = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    [[manger dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        // AFN获取响应头 https://www.jianshu.com/p/a9f09052eaed
        NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;
        NSString *token = httpRes.allHeaderFields[@"Authorization"];
        NSLog(@"token:%@",token);
        
        if (!error) {
            if (success) {
                success(responseObject);
            }
        }else{
            if (failure) {
                
                failure(error);
            }
        }
        // 最后一定要启动,不然方法不走。
    }] resume];
}


    // 将Dic转为JSON
+ (NSString *)rb_jsonStrFromDic:(NSDictionary *)dic{
    
    if (dic == nil) return nil;
    
    NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    
    if (err) {
        NSLog(@"转JSON失败:%@",err);
        return nil;
    }
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"请求参数:%@",jsonStr);
    
    return jsonStr;
}

    

// 设置请求头的GET请求
+ (void)rb_GET_haveRequestHeader:(NSString *)urlStr pardic:(NSDictionary *)dic authorization:(NSString *)authori successHandler:(FDHttpSuccessBlock)success failureHandler:(FDHttpFailureBlock)failure {
    
    NSMutableURLRequest *requestM = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlStr parameters:dic error:nil];
    // 设置请求头:token包含在请求头中
//    [requestM setValue:[self rb_token] forHTTPHeaderField:@"Authorization"];
    [requestM setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestM setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [requestM setValue:@"zh-CN" forHTTPHeaderField:@"Accept-Language"]; //中文：zh-CN，英文：en-US
    [requestM setValue:@"1.1" forHTTPHeaderField:@"Authorization-Version"];//客户端版本
    [requestM setValue:authori forHTTPHeaderField:@"Authorization"];//

    
    AFURLSessionManager *manger = [[AFURLSessionManager  alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    [[manger dataTaskWithRequest:requestM completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            if (success) {
                success(responseObject);
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }] resume];
}




@end
